import { useState, useEffect } from "react";
import {
  Status,
  useStatus,
  useSpeed,
  useSpeedAction,
  useLayout,
  useCheckCollision,
} from "./../../context";
import config from "../../config";
import { getRandomPoint } from "../../utils";

/** 食物生成 */
export default function useFoodGenerate(count: number) {
  const status = useStatus();
  const speed = useSpeed();
  const setSpeed = useSpeedAction();
  const { gridSize, stageSize } = useLayout();
  const [points, setPoints] = useState(createPoints);
  const { isCollision, collisionPoint } = useCheckCollision();

  // 创建食物
  function createPoints() {
    return Array.from({ length: count }).map(() =>
      getRandomPoint(gridSize, gridSize, stageSize, stageSize)
    );
  }

  // 重置食物
  useEffect(() => {
    if (status === Status.reset) {
      setPoints(createPoints);
      setSpeed(config.speed);
    }
  }, [status]);

  // 递减食物
  useEffect(() => {
    if (status === Status.start) {
      setPoints(
        points.filter((point) => {
          if (point.x === collisionPoint.x && point.y === collisionPoint.y) {
            return false;
          }
          return true;
        })
      );
    }
  }, [status, isCollision]);

  // 重新生成食物
  useEffect(() => {
    if ((status === Status.start && points.length) === 0) {
      setPoints(createPoints);
      setSpeed((speed * config.speedRatio) >> 0);
    }
  }, [status, points]);

  return points;
}
